package com.avecsys.quotemanager.mbeans.supplier;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.icefaces.ace.json.JSONException;
import org.icefaces.ace.json.JSONObject;

import com.avecsys.quotemanager.dao.common.EnumActor;
import com.avecsys.quotemanager.exception.BaseException;
import com.avecsys.quotemanager.exception.BusinessException;
import com.avecsys.quotemanager.mbeans.core.BaseMBean;
import com.avecsys.quotemanager.pojos.SupplierMasterPojo;
import com.avecsys.quotemanager.pojos.SupplierUsersPojo;
import com.avecsys.quotemanager.service.common.CommonService;
import com.avecsys.quotemanager.service.supplier.SupplierMasterService;
import com.avecsys.quotemanager.service.user.UserMasterService;
import com.avecsys.quotemanager.utils.MessageBoardUtil;
import com.avecsys.quotemanager.utils.TransactionStatus;

/**
 * @author Sam Sundar
 * 
 */
public class SupplierUsersListMBean extends BaseMBean implements Serializable {
	private final Log log = LogFactory.getLog(SupplierUsersListMBean.class);

	private SupplierMasterPojo selectedSupplier;

	private SupplierMasterService supplierMasterService;

	private UserMasterService userMasterService;

	private CommonService commonService;

	private List<SupplierUsersPojo> supplierUsersPojoList = new ArrayList<SupplierUsersPojo>();

	public SupplierUsersListMBean() {
		super();
	}

	/**
	 * Action method to open the add user screen for a supplier
	 * 
	 * @return String
	 */
	public String actionAddUser() {
		FacesContext faceContext = FacesContext.getCurrentInstance();
		Map<String, String> paramValues = faceContext.getExternalContext()
				.getRequestParameterMap();
		String selectedSupplierId = paramValues.get("selectedSupplierId");
		String selectedSupplierCompanyName = paramValues
				.get("selectedSupplierCompanyName");
		SupplierUsersMBean supplierUsersMBean = (SupplierUsersMBean) faceContext
				.getApplication().evaluateExpressionGet(faceContext,
						"#{supplierUsersMBean}", SupplierUsersMBean.class);
		supplierUsersMBean.setSelectedSupplierId(selectedSupplierId);
		supplierUsersMBean
				.setSelectedSupplierCompanyName(selectedSupplierCompanyName);
		supplierUsersMBean.setSupplierUsersPojo(new SupplierUsersPojo());
		return "openAddUserForSupplier";
	}

	public String actionCancel() {
		return "openListAllSuppliers";
	}

	/**
	 * Method to delete the selected supplier user
	 * 
	 * @param actionEvent
	 */
	public void actionDeleteSupplierUser(ActionEvent actionEvent) {
		MessageBoardUtil.resetMessageBoard();
		String requestJSON = getMessageDialog().getRequestJSON();
		JSONObject requestJSONObject;
		String supplierUserId = null;
		try {
			requestJSONObject = new JSONObject(requestJSON);
			supplierUserId = (String) requestJSONObject.get("supplierUserId");
			SupplierUsersPojo supplierUsersPojo = userMasterService
					.getSupplierUserById(new Long(supplierUserId));
			SupplierMasterPojo supplierMasterPojo = supplierUsersPojo
					.getSupplierMasterPojo();
			TransactionStatus transactionStatus = userMasterService
					.deleteSupplierUser(supplierUsersPojo);
			loadAllUsersBySupplier(supplierMasterPojo);
			MessageBoardUtil.publishTransactionStatusMessage(transactionStatus,
					EnumActor.SUPPLIER_USER, "messageBoardId", "",
					new Object[] { supplierUsersPojo.getUserMasterPojo()
							.getUserName() });
		} catch (BusinessException e) {
			log.error(e);
		} catch (Exception e) {
			log.error(e);
		}
		getMessageDialog().hideDialog();
	}

	/**
	 * Action Method to send verification email to Supplier user
	 * 
	 * @param actionEvent
	 */
	public void actionSendVerificationEmail(ActionEvent actionEvent) {
		MessageBoardUtil.resetMessageBoard();
		FacesContext faceContext = FacesContext.getCurrentInstance();
		Map<String, String> paramValues = faceContext.getExternalContext()
				.getRequestParameterMap();
		String supplierUserId = (String) paramValues.get("supplierUserId");
		SupplierUsersPojo supplierUsersPojo = null;
		try {
			supplierUsersPojo = userMasterService.getSupplierUserById(new Long(
					supplierUserId));
			// Send Verification Email only when if it is not already verified
			commonService.sendEmail(supplierUsersPojo);
		} catch (BaseException e) {
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
		try {
			if (supplierUsersPojo != null) {
				loadAllUsersBySupplier(supplierUsersPojo
						.getSupplierMasterPojo());
			}
		} catch (BusinessException e) {
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
	}

	/**
	 * Method to show the confirm dialog request to delete supplier user
	 * 
	 * @param actionEvent
	 */
	public void confirmDeleteAction(ActionEvent actionEvent) {
		FacesContext faceContext = FacesContext.getCurrentInstance();
		Map<String, String> paramValues = faceContext.getExternalContext()
				.getRequestParameterMap();
		String supplierUserId = (String) paramValues.get("supplierUserId");
		String selectedSupplierId = (String) paramValues
				.get("selectedSupplierId");
		String userName = (String) paramValues.get("userName");
		JSONObject requestJSONObject = new JSONObject();
		try {
			requestJSONObject.put("supplierId", selectedSupplierId);
			requestJSONObject.put("supplierUserId", supplierUserId);
			requestJSONObject.put("companyName", userName);
			getMessageDialog().setRequestJSON(requestJSONObject.toString());
			getMessageDialog().setMessage(
					"Are you sure to delete '" + userName + "' ?");
		} catch (JSONException e) {
			log.error(e);
		}
		getMessageDialog().showDialog();
	}

	/**
	 * Edits the supplier user information
	 * 
	 * @return
	 */
	public String editSupplierUser() {
		FacesContext faceContext = FacesContext.getCurrentInstance();
		Map<String, String> paramValues = faceContext.getExternalContext()
				.getRequestParameterMap();
		String selectedSupplierId = paramValues.get("selectedSupplierId");
		String selectedSupplierCompanyName = paramValues
				.get("selectedSupplierCompanyName");
		String supplierUserId = (String) paramValues.get("supplierUserId");
		try {
			SupplierUsersMBean supplierUsersMBean = (SupplierUsersMBean) faceContext
					.getApplication().evaluateExpressionGet(faceContext,
							"#{supplierUsersMBean}", SupplierUsersMBean.class);
			supplierUsersMBean.setSelectedSupplierId(selectedSupplierId);
			supplierUsersMBean
					.setSelectedSupplierCompanyName(selectedSupplierCompanyName);
			SupplierUsersPojo supplierUsersPojo = userMasterService
					.getSupplierUserById(Long.parseLong(supplierUserId));
			supplierUsersMBean.setSupplierUsersPojo(supplierUsersPojo);
			// preserve the the email address to identify user has changed the
			// email address
			supplierUsersMBean.setExistingEmailAddress(supplierUsersPojo
					.getUserMasterPojo().getEmail());
			supplierUsersMBean.setScreenModeEdit(true);
		} catch (BusinessException e) {
			log.error(e);
		} catch (Exception e) {
			log.error(e);
		}
		return "openEditUserForSupplier";
	}

	public CommonService getCommonService() {
		return commonService;
	}

	/**
	 * @return the selectedSupplier
	 */
	public SupplierMasterPojo getSelectedSupplier() {
		return selectedSupplier;
	}

	/**
	 * @return the supplierMasterService
	 */
	public SupplierMasterService getSupplierMasterService() {
		return supplierMasterService;
	}

	public List<SupplierUsersPojo> getSupplierUsersPojoList() {
		return supplierUsersPojoList;
	}

	/**
	 * @return the userMasterService
	 */
	public UserMasterService getUserMasterService() {
		return userMasterService;
	}

	/**
	 * Method to load all the users for a supplier
	 * 
	 * @param supplierMasterPojo
	 * @throws BusinessException
	 */
	public void loadAllUsersBySupplier(SupplierMasterPojo supplierMasterPojo)
			throws BusinessException {
		setSupplierUsersPojoList(supplierMasterService
				.getAllUsers(supplierMasterPojo));
		setSelectedSupplier(supplierMasterPojo);
	}

	public void setCommonService(CommonService commonService) {
		this.commonService = commonService;
	}

	/**
	 * @param selectedSupplier
	 *            the selectedSupplier to set
	 */
	public void setSelectedSupplier(SupplierMasterPojo selectedSupplier) {
		this.selectedSupplier = selectedSupplier;
	}

	/**
	 * @param supplierMasterService
	 *            the supplierMasterService to set
	 */
	public void setSupplierMasterService(
			SupplierMasterService supplierMasterService) {
		this.supplierMasterService = supplierMasterService;
	}

	public void setSupplierUsersPojoList(
			List<SupplierUsersPojo> supplierUsersPojoList) {
		this.supplierUsersPojoList = supplierUsersPojoList;
	}

	/**
	 * @param userMasterService
	 *            the userMasterService to set
	 */
	public void setUserMasterService(UserMasterService userMasterService) {
		this.userMasterService = userMasterService;
	}
}
